package com.coding4play.mqtt.store.impl;

import com.coding4play.mqtt.common.repository.IMessageIdService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * 通过redis返回一个数据id
 */
@Component
@AllArgsConstructor
@Slf4j
public class MessageIdServiceImpl implements IMessageIdService<Integer> {

    private final static String KV_MESSAGE_ID_CACHE = "mqtt:messageId:number";

    private StringRedisTemplate redisTemplate;

    @Override
    public Integer nextMessageId() {
        try {
            while (true) {
                Long increment = redisTemplate.opsForValue().increment(KV_MESSAGE_ID_CACHE);
                int nextMsgId = (int) (increment % 65536);
                if (nextMsgId > 0) {
                    return nextMsgId;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return 0;
    }

    /**
     * 每次重启的时候初始化
     */
    @PostConstruct
    public void init() {
        redisTemplate.delete(KV_MESSAGE_ID_CACHE);
    }
}
